{% extends "base.html" %}

{% block title %}{{ tool.name if tool else '工具' }} - 个人工具网站集{% endblock %}

{% block content %}
<div class="min-h-screen bg-gray-50">
    {% if tool %}
        <!-- 工具详情页 -->
        <div class="bg-white border-b border-gray-200">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
                <div class="flex items-center justify-between">
                    <div class="flex items-center space-x-4">
                        <a href="{{ url_for('index') }}" 
                           class="text-gray-500 hover:text-gray-700 transition-colors">
                            <i class="fas fa-arrow-left mr-2"></i>返回首页
                        </a>
                        <div class="h-6 border-l border-gray-300"></div>
                        <div>
                            <h1 class="text-2xl font-bold text-gray-900">{{ tool.name }}</h1>
                            <p class="text-gray-600 mt-1">{{ tool.description or '暂无描述' }}</p>
                        </div>
                    </div>
                    
                    <div class="flex items-center space-x-4">
                        <!-- 工具信息 -->
                        <div class="flex items-center space-x-6 text-sm text-gray-500">
                            <div class="flex items-center">
                                <i class="fas fa-eye mr-1"></i>
                                <span>{{ tool.views or 0 }} 次访问</span>
                            </div>
                            <div class="flex items-center">
                                <i class="fas fa-heart mr-1"></i>
                                <span>{{ tool.likes or 0 }} 点赞</span>
                            </div>
                            <div class="flex items-center">
                                <i class="fas fa-calendar mr-1"></i>
                                <span>{{ tool.created_at.strftime('%Y-%m-%d') if tool.created_at else '未知' }}</span>
                            </div>
                        </div>
                        
                        <!-- 操作按钮 -->
                        <div class="flex items-center space-x-2">
                            <button onclick="likeTool()" id="likeBtn" 
                                    class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors">
                                <i class="fas fa-heart mr-2"></i>点赞
                            </button>
                            <button onclick="shareTool()" 
                                    class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors">
                                <i class="fas fa-share mr-2"></i>分享
                            </button>
                            {% if current_user and current_user.id == tool.user_id %}
                            <button onclick="editTool()" 
                                    class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
                                <i class="fas fa-edit mr-2"></i>编辑
                            </button>
                            {% endif %}
                        </div>
                    </div>
                </div>
                
                <!-- 标签 -->
                {% if tool.tags %}
                <div class="mt-4">
                    <div class="flex flex-wrap gap-2">
                        {% for tag in tool.tags.split(',') if tag.strip() %}
                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                            <i class="fas fa-tag mr-1"></i>{{ tag.strip() }}
                        </span>
                        {% endfor %}
                    </div>
                </div>
                {% endif %}
            </div>
        </div>
        
        <!-- 工具内容区域 -->
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                <!-- 工具栏 -->
                <div class="bg-gray-50 border-b border-gray-200 px-6 py-4">
                    <div class="flex items-center justify-between">
                        <div class="flex items-center space-x-4">
                            <div class="flex items-center space-x-2">
                                <div class="w-3 h-3 bg-red-500 rounded-full"></div>
                                <div class="w-3 h-3 bg-yellow-500 rounded-full"></div>
                                <div class="w-3 h-3 bg-green-500 rounded-full"></div>
                            </div>
                            <div class="text-sm text-gray-600">
                                <i class="fas fa-globe mr-2"></i>{{ tool.name }}
                            </div>
                        </div>
                        
                        <div class="flex items-center space-x-2">
                            <button onclick="refreshTool()" 
                                    class="p-2 text-gray-500 hover:text-gray-700 transition-colors" 
                                    title="刷新">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                            <button onclick="openInNewTab()" 
                                    class="p-2 text-gray-500 hover:text-gray-700 transition-colors" 
                                    title="在新标签页中打开">
                                <i class="fas fa-external-link-alt"></i>
                            </button>
                            <button onclick="toggleFullscreen()" 
                                    class="p-2 text-gray-500 hover:text-gray-700 transition-colors" 
                                    title="全屏">
                                <i class="fas fa-expand"></i>
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- iframe容器 -->
                <div class="relative" id="toolContainer">
                    <iframe id="toolFrame" 
                            src="{{ url_for('view_tool_content', tool_id=tool.id) }}" 
                            class="w-full border-0" 
                            style="height: 80vh; min-height: 600px;"
                            onload="handleFrameLoad()"
                            onerror="handleFrameError()">
                    </iframe>
                    
                    <!-- 加载状态 -->
                    <div id="loadingOverlay" class="absolute inset-0 bg-white flex items-center justify-center">
                        <div class="text-center">
                            <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
                            <p class="text-gray-600">正在加载工具...</p>
                        </div>
                    </div>
                    
                    <!-- 错误状态 -->
                    <div id="errorOverlay" class="absolute inset-0 bg-white flex items-center justify-center hidden">
                        <div class="text-center">
                            <div class="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
                                <i class="fas fa-exclamation-triangle text-red-600 text-2xl"></i>
                            </div>
                            <h3 class="text-lg font-semibold text-gray-900 mb-2">加载失败</h3>
                            <p class="text-gray-600 mb-4">工具加载出现问题，请稍后重试</p>
                            <button onclick="refreshTool()" 
                                    class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
                                <i class="fas fa-sync-alt mr-2"></i>重新加载
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 相关工具推荐 -->
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                <h3 class="text-lg font-semibold text-gray-900 mb-6">
                    <i class="fas fa-lightbulb text-yellow-500 mr-2"></i>相关工具推荐
                </h3>
                
                <div id="relatedTools" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    <!-- 相关工具将通过JavaScript动态加载 -->
                    <div class="text-center py-8 col-span-full">
                        <i class="fas fa-tools text-4xl text-gray-300 mb-4"></i>
                        <p class="text-gray-500">正在加载相关工具...</p>
                    </div>
                </div>
            </div>
        </div>
        
    {% else %}
        <!-- 工具不存在 -->
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16">
            <div class="text-center">
                <div class="w-24 h-24 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-6">
                    <i class="fas fa-search text-gray-400 text-3xl"></i>
                </div>
                <h2 class="text-2xl font-bold text-gray-900 mb-4">工具不存在</h2>
                <p class="text-gray-600 mb-8">抱歉，您访问的工具不存在或已被删除。</p>
                <div class="space-x-4">
                    <a href="{{ url_for('index') }}" 
                       class="inline-flex items-center px-6 py-3 border border-transparent text-base font-medium rounded-lg text-white bg-blue-600 hover:bg-blue-700 transition-colors">
                        <i class="fas fa-home mr-2"></i>返回首页
                    </a>
                    <a href="{{ url_for('profile') }}" 
                       class="inline-flex items-center px-6 py-3 border border-gray-300 text-base font-medium rounded-lg text-gray-700 bg-white hover:bg-gray-50 transition-colors">
                        <i class="fas fa-upload mr-2"></i>上传工具
                    </a>
                </div>
            </div>
        </div>
    {% endif %}
</div>

<!-- 分享模态框 -->
<div id="shareModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
    <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-lg bg-white">
        <div class="mt-3">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-semibold text-gray-900">
                    <i class="fas fa-share mr-2 text-blue-600"></i>分享工具
                </h3>
                <button onclick="closeShareModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">分享链接</label>
                    <div class="flex">
                        <input type="text" id="shareUrl" readonly 
                               class="flex-1 px-3 py-2 border border-gray-300 rounded-l-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                               value="{{ request.url if tool else '' }}">
                        <button onclick="copyShareUrl()" 
                                class="px-4 py-2 bg-blue-600 text-white rounded-r-lg hover:bg-blue-700 transition-colors">
                            <i class="fas fa-copy"></i>
                        </button>
                    </div>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">社交分享</label>
                    <div class="flex space-x-2">
                        <button onclick="shareToWeChat()" 
                                class="flex-1 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors">
                            <i class="fab fa-weixin mr-2"></i>微信
                        </button>
                        <button onclick="shareToQQ()" 
                                class="flex-1 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors">
                            <i class="fab fa-qq mr-2"></i>QQ
                        </button>
                        <button onclick="shareToWeibo()" 
                                class="flex-1 px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors">
                            <i class="fab fa-weibo mr-2"></i>微博
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let isFullscreen = false;

// 处理iframe加载完成
function handleFrameLoad() {
    document.getElementById('loadingOverlay').style.display = 'none';
    
    // 记录访问
    {% if tool %}
    fetch('{{ url_for("record_tool_view", tool_id=tool.id) }}', {
        method: 'POST'
    });
    {% endif %}
}

// 处理iframe加载错误
function handleFrameError() {
    document.getElementById('loadingOverlay').style.display = 'none';
    document.getElementById('errorOverlay').classList.remove('hidden');
}

// 刷新工具
function refreshTool() {
    const frame = document.getElementById('toolFrame');
    const loadingOverlay = document.getElementById('loadingOverlay');
    const errorOverlay = document.getElementById('errorOverlay');
    
    loadingOverlay.style.display = 'flex';
    errorOverlay.classList.add('hidden');
    
    frame.src = frame.src;
}

// 在新标签页中打开
function openInNewTab() {
    {% if tool %}
    window.open('{{ url_for("view_tool_content", tool_id=tool.id) }}', '_blank');
    {% endif %}
}

// 切换全屏
function toggleFullscreen() {
    const container = document.getElementById('toolContainer');
    const frame = document.getElementById('toolFrame');
    const btn = event.target.closest('button');
    
    if (!isFullscreen) {
        // 进入全屏
        container.classList.add('fixed', 'inset-0', 'z-50', 'bg-white');
        frame.style.height = '100vh';
        btn.innerHTML = '<i class="fas fa-compress"></i>';
        btn.title = '退出全屏';
        isFullscreen = true;
    } else {
        // 退出全屏
        container.classList.remove('fixed', 'inset-0', 'z-50', 'bg-white');
        frame.style.height = '80vh';
        btn.innerHTML = '<i class="fas fa-expand"></i>';
        btn.title = '全屏';
        isFullscreen = false;
    }
}

// 点赞工具
function likeTool() {
    {% if tool %}
    const btn = document.getElementById('likeBtn');
    btn.disabled = true;
    
    fetch('{{ url_for("like_tool", tool_id=tool.id) }}', {
        method: 'POST'
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            btn.innerHTML = '<i class="fas fa-heart text-red-500 mr-2"></i>已点赞';
            btn.classList.add('text-red-600', 'border-red-300');
            showSuccessMessage('点赞成功！');
        } else {
            showErrorMessage(data.message || '点赞失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showErrorMessage('网络错误，请重试');
    })
    .finally(() => {
        btn.disabled = false;
    });
    {% endif %}
}

// 分享工具
function shareTool() {
    document.getElementById('shareModal').classList.remove('hidden');
}

// 关闭分享模态框
function closeShareModal() {
    document.getElementById('shareModal').classList.add('hidden');
}

// 复制分享链接
function copyShareUrl() {
    const input = document.getElementById('shareUrl');
    input.select();
    document.execCommand('copy');
    showSuccessMessage('链接已复制到剪贴板！');
}

// 分享到微信
function shareToWeChat() {
    // 这里可以集成微信分享SDK
    showInfoMessage('请复制链接手动分享到微信');
}

// 分享到QQ
function shareToQQ() {
    {% if tool %}
    const url = encodeURIComponent(window.location.href);
    const title = encodeURIComponent('{{ tool.name }}');
    const desc = encodeURIComponent('{{ tool.description or "" }}');
    window.open(`https://connect.qq.com/widget/shareqq/index.html?url=${url}&title=${title}&desc=${desc}`);
    {% endif %}
}

// 分享到微博
function shareToWeibo() {
    {% if tool %}
    const url = encodeURIComponent(window.location.href);
    const title = encodeURIComponent('{{ tool.name }} - {{ tool.description or "" }}');
    window.open(`https://service.weibo.com/share/share.php?url=${url}&title=${title}`);
    {% endif %}
}

// 编辑工具
function editTool() {
    {% if tool %}
    window.location.href = '{{ url_for("edit_tool", tool_id=tool.id) }}';
    {% endif %}
}

// 显示成功消息
function showSuccessMessage(message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = 'fixed top-4 right-4 bg-green-500 text-white px-6 py-3 rounded-lg shadow-lg z-50';
    alertDiv.innerHTML = `<i class="fas fa-check-circle mr-2"></i>${message}`;
    
    document.body.appendChild(alertDiv);
    
    setTimeout(() => {
        alertDiv.remove();
    }, 5000);
}

// 显示错误消息
function showErrorMessage(message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = 'fixed top-4 right-4 bg-red-500 text-white px-6 py-3 rounded-lg shadow-lg z-50';
    alertDiv.innerHTML = `<i class="fas fa-exclamation-circle mr-2"></i>${message}`;
    
    document.body.appendChild(alertDiv);
    
    setTimeout(() => {
        alertDiv.remove();
    }, 5000);
}

// 显示信息消息
function showInfoMessage(message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = 'fixed top-4 right-4 bg-blue-500 text-white px-6 py-3 rounded-lg shadow-lg z-50';
    alertDiv.innerHTML = `<i class="fas fa-info-circle mr-2"></i>${message}`;
    
    document.body.appendChild(alertDiv);
    
    setTimeout(() => {
        alertDiv.remove();
    }, 5000);
}

// 加载相关工具
function loadRelatedTools() {
    {% if tool %}
    fetch('{{ url_for("get_related_tools", tool_id=tool.id) }}')
    .then(response => response.json())
    .then(data => {
        const container = document.getElementById('relatedTools');
        
        if (data.tools && data.tools.length > 0) {
            container.innerHTML = '';
            data.tools.forEach(tool => {
                const toolCard = createToolCard(tool);
                container.appendChild(toolCard);
            });
        } else {
            container.innerHTML = `
                <div class="text-center py-8 col-span-full">
                    <i class="fas fa-tools text-4xl text-gray-300 mb-4"></i>
                    <p class="text-gray-500">暂无相关工具</p>
                </div>
            `;
        }
    })
    .catch(error => {
        console.error('Error loading related tools:', error);
        document.getElementById('relatedTools').innerHTML = `
            <div class="text-center py-8 col-span-full">
                <i class="fas fa-exclamation-triangle text-4xl text-red-300 mb-4"></i>
                <p class="text-gray-500">加载相关工具失败</p>
            </div>
        `;
    });
    {% endif %}
}

// 创建工具卡片
function createToolCard(tool) {
    const card = document.createElement('div');
    card.className = 'bg-white border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer';
    card.onclick = () => window.location.href = `/tool/${tool.id}`;
    
    card.innerHTML = `
        <div class="flex items-center mb-3">
            <div class="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center mr-3">
                <i class="fas fa-tools text-blue-600"></i>
            </div>
            <div class="flex-1">
                <h4 class="font-medium text-gray-900">${tool.name}</h4>
                <p class="text-sm text-gray-500">${tool.category || '其他'}</p>
            </div>
        </div>
        <p class="text-sm text-gray-600 mb-3">${tool.description || '暂无描述'}</p>
        <div class="flex items-center justify-between text-xs text-gray-500">
            <span><i class="fas fa-eye mr-1"></i>${tool.views || 0}</span>
            <span><i class="fas fa-heart mr-1"></i>${tool.likes || 0}</span>
        </div>
    `;
    
    return card;
}

// 页面加载时的初始化
document.addEventListener('DOMContentLoaded', function() {
    // 加载相关工具
    loadRelatedTools();
    
    // 键盘快捷键
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && isFullscreen) {
            toggleFullscreen();
        }
        if (e.key === 'F11') {
            e.preventDefault();
            toggleFullscreen();
        }
    });
});
</script>
{% endblock %}